<template>
  <view class="">
    <u-navbar title="分类" :is-back="false" :background="background" titleColor="#fff"></u-navbar>
    <view class="u-wrap">
      <!-- 固定搜索框 -->
      <view class="u-search-box" style="position: sticky; top: 0; z-index: 10;" @click="toSearch">
        <view class="u-search-inner">
          <u-icon name="search" color="#909399" :size="28"></u-icon>
          <text class="u-search-text">请输入关键词搜索</text>
        </view>
      </view>
      <view class="u-menu-wrap">
        <scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop">
          <view v-for="(remark, index) in uniqueRemarks" :key="index" class="u-tab-item" :class="[current == index ? 'u-tab-item-active' : '']"
            :data-current="index" @tap.stop="swichMenu(index)">
            <text class="u-line-1">{{ remark }}</text>
          </view>
        </scroll-view>
        <scroll-view scroll-y class="right-box">
          <view class="page-view">
            <view v-for="(remark, index) in uniqueRemarks" :key="index" class="class-item" :ref="`category-${index}`" v-show="current === index">
              <view class="item-title">
                <text>{{ remark }}</text>
              </view>
              <view class="item-container">
                <view class="thumb-box" v-for="(dish, index1) in getCategoryDishes(remark)" :key="index1" @click="toDetail(dish.id)">
                  <image class="item-menu-image" :src="dish.cover_img"></image>
                  <view class="item-menu-name">{{ dish.name }}</view>
                  <view class="item-menu-price">￥{{ dish.price }}</view>
                </view>
              </view>
            </view>
            <view v-if="!uniqueRemarks.length" class="no-data">
              <text>暂无商品信息</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>
<script>
	import {http} from "@/utils/request.js"
	
export default {
  data() {
    return {
      img: '/static/pic.jpg',
      background: {
        'background-image': 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
      },
      scrollTop: 0,
      oldScrollTop: 0,
      current: 0,
      menuHeight: 0,
      menuItemHeight: 0,
      itemId: '',
      categories: [], // 存储从后端获取的分类数据
      allDishes: [], // 存储所有商品数据
      selectedCategoryDishes: [], // 存储当前选中分类下的商品数据
      uniqueRemarks: [], // 存储唯一的 remark 字段
      tabbar: [],
      menuItemPos: [],
      arr: [],
      scrollRightTop: 0,
      timer: null,
    }
  },
  onLoad() {
    this.loadAllDishes(); // 组件加载时调用加载所有商品的方法
  },
  methods: {
    toSearch() {
      uni.navigateTo({
        url: '/pages/index/search'
      });
    },
    toDetail(id) {
      uni.navigateTo({
        url: `/pages/index/list?id=${id}`
      });
    },
    async swichMenu(index) {
      if (index === this.current) return;
      this.current = index;
      const remark = this.uniqueRemarks[index];
      this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
      this.scrollToCategory(index);
    },
    scrollToCategory(index) {
      this.$nextTick(() => {
        const ref = this.$refs[`category-${index}`][0];
        if (ref) {
          ref.$el.scrollIntoView({ behavior: 'smooth' });
        }
      });
    },
    getElRect(elClass, dataVal) {
      return new Promise((resolve, reject) => {
        const query = uni.createSelectorQuery().in(this);
        query.select('.' + elClass).fields({ size: true }, res => {
          if (!res) {
            setTimeout(() => {
              this.getElRect(elClass, dataVal).then(resolve).catch(reject);
            }, 10);
            return;
          }
          this[dataVal] = res.height;
          resolve();
        }).exec();
      });
    },
    async loadAllDishes() {
      try {
		  uni.request({
		  	url: 'http://localhost:8084/good/getgood',
		  	method: 'GET',
		  	success: (response) => {
		  		console.log('Response:', response);
		  		if (response.data && response.data.status === 1) {
		  		  this.allDishes = response.data.data.map(item => ({
		  		    ...item,
		  		    cover_img: item.cover_img || '/static/default-image.jpg' // 处理可能为空的图片路径
		  		  }));
		  		  this.uniqueRemarks = Array.from(new Set(this.allDishes.map(dish => dish.remark)));
		  		  console.log('Loaded all dishes:', this.allDishes);
		  		  console.log('Unique remarks:', this.uniqueRemarks);
		  		} else {
		  		  console.error('Failed to load all dishes:', response.data.message);
		  		}
		  	},
		  	fail: (err) => {
		  		console.error(err);
		  	}
		  }); 
      } catch (error) {
        console.error('Failed to load all dishes:', error);
      }
    },
    getCategoryDishes(remark) {
      return this.allDishes.filter(dish => dish.remark === remark);
    }
  }
}
</script>
<style lang="scss" scoped>
.u-wrap {
  height: calc(100vh);
  /* #ifdef H5 */
  height: calc(100vh - var(--window-top));
  /* #endif */
  display: flex;
  flex-direction: column;
}

.u-search-box {
  padding: 18rpx 30rpx;
  background-color: #fff; /* 搜索框背景颜色 */
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  z-index: 10; /* 确保搜索框在最上方 */
  position: sticky;
  top: 0;
}

.u-search-inner {
  background-color: rgb(234, 234, 234);
  border-radius: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16rpx 16rpx;
}

.u-search-text {
  font-size: 26rpx;
  color: #909399;
  margin-left: 10rpx;
}

.u-menu-wrap {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.u-tab-view {
  width: 200rpx;
  height: 100%;
  overflow-y: auto;
  flex-shrink: 0; /* 防止左侧分类栏被压缩 */
}

.u-tab-item {
  height: 110rpx;
  background: #f6f6f6;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  color: #444;
  font-weight: 400;
  line-height: 1;
}

.u-tab-item-active {
  position: relative;
  color: #6BC362;
  font-size: 30rpx;
  font-weight: 600;
  background: #fff;
}

.u-tab-item-active::before {
  content: "";
  position: absolute;
  border-left: 4px solid #6BC362;
  height: 32rpx;
  left: 0;
  top: 39rpx;
}

.right-box {
  flex: 1;
  background-color: rgb(250, 250, 250);
  padding: 16rpx;
  overflow-y: auto; /* 确保右侧内容可滚动 */
}

.page-view {
  height: 100%;
}

.class-item {
  margin-bottom: 30rpx;
  background-color: #fff;
  padding: 16rpx;
  border-radius: 8rpx;
}

.item-title {
  font-size: 26rpx;
  color: #444;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.item-container {
  display: flex;
  flex-wrap: wrap;
}

.thumb-box {
  width: 33.333333%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20rpx;
}

.item-menu-image {
  width: 150rpx;
  height: 150rpx;
  border-radius: 6rpx;
  margin-bottom: 10rpx;
}

.item-menu-name {
  font-size: 24rpx;
  color: #444;
  text-align: center;
}

.item-menu-price {
  font-size: 22rpx;
  color: #ff5722;
  text-align: center;
}

.no-data {
  text-align: center;
  font-size: 28rpx;
  color: #999;
  margin-top: 50rpx;
}
</style>